问题

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Here are few examples.

[1,3,5,6], 5 → 2

[1,3,5,6], 2 → 1

[1,3,5,6], 7 → 4

[1,3,5,6], 0 → 0

思路

这个问题的思路很简单,就是二分查找,而且直接套用框架就行了

代码

  1. public class Solution {
  2. public int searchInsert(int[] nums, int target) {
  3. int st,ed,mid;
  4. st = 0;
  5. ed = nums.length;
  6. while(st < ed)
  7. {
  8. mid = st + (ed - st)/2;
  9. if(nums[mid] < target)
  10. st = mid+1;
  11. else
  12. ed = mid;
  13. }
  14. return st;
  15. }
  16. }